let express = require("express");
let uunewid = require("uuid");
let router = express.Router();
let log = require("cf-nodejs-logging-support");
log.setLoggingLevel("info");

const { ohana } = require("ohana-node-orm");
const tableName = "SAP_JIANGDU_WORKTABLE";
const ohana_instance = new ohana(tableName);

const { checkAuth } = require("../utils/utils");
let constants = require("../utils/constants");

router.get("/allServices", function (req, res, next) {
    // #swagger.tags = ['定时任务']
    // #swagger.summary = '获取该user所有的AS TE TA'
    // #swagger.description = '需要JWT Token'
    /* #swagger.security = [{
                   "JiangduJWT": []
      }] */
    const user = checkAuth(req.user, constants.BASICAUTH);

    if (!user.authCheck) {
        res.sendStatus(403);
    }

    let payload = {};
    payload.USER_ID_USER_ID = user.user_id;
    payload.STATUS = "on";

    getAllServices(payload)
        .then((result) => {
            res.send(result);
        })
        .catch((err) => {
            log.error(err);
            res.status(500).send(err);
        });
});

async function getAllServices(condition) {
    const ohana_instance1 = new ohana("SAP_JIANGDU_ASSETS");
    // const ohana_instance2 = new ohana("SAP_JIANGDU_JINRONGHUIQIS");
    // const ohana_instance3 = new ohana("SAP_JIANGDU_POLICYS");
    const ohana_instance4 = new ohana("SAP_JIANGDU_TECH_INNOS");
    const ohana_instance5 = new ohana("SAP_JIANGDU_TALENTS");
    result1 = await ohana_instance1.find(condition);
    // result2 = await ohana_instance2.find(condition);
    // result3 = await ohana_instance3.find(condition);
    result4 = await ohana_instance4.find(condition);
    result5 = await ohana_instance5.find(condition);
    result = {
        AS: result1,
        TE: result4,
        TA: result5,
    };
    return result;
}

router.get("/", function (req, res, next) {
    // #swagger.tags = ['定时任务']
    // #swagger.summary = '获取列表'
    // #swagger.description = '需要JWT Token'
    /* #swagger.security = [{
                   "JiangduJWT": []
      }] */
    const user = checkAuth(req.user, constants.BASICAUTH);

    if (!user.authCheck) {
        res.sendStatus(403);
    }

    let payload = {};
    let { TYPE, USER_ID } = req.query;
    if (TYPE) {
        payload.TYPE = TYPE;
    }

    if (USER_ID) {
        payload.USER_ID = USER_ID;
    }

    getData(payload)
        .then((result) => {
            res.send(result);
        })
        .catch((err) => {
            log.error(err);
            res.status(500).send(err);
        });
});

router.post("/", function (req, res, next) {
    // #swagger.tags = ['定时任务']
    // #swagger.summary = '插入列表'
    /* #swagger.security = [{
                   "JiangduJWT": []
      }] */
    /*	#swagger.requestBody = {
                  required: true,
                  content: {
                      "application/json": {
                          schema: {
                              $ref: "#/definitions/worktable_add"
                          }  
                      },
                  }
          } */
    let { data } = req.body;

    // 没有结束日期默认9999年
    if (!data.END_DATE) {
        data.END_DATE = "9999-1-1";
    }

    insertData(data)
        .then((result) => {
            if (result == 1) {
                res.sendStatus(200);
            } else {
                res.sendStatus(500);
            }
        })
        .catch((err) => {
            log.error(err);
            res.status(500).send(err);
        });
});

router.post("/addCount", function (req, res, next) {
    // #swagger.tags = ['定时任务']
    // #swagger.summary = '触发任务'
    /* #swagger.security = [{
                   "JiangduJWT": []
      }] */
    /*	#swagger.requestBody = {
                  required: true,
                  content: {
                      "application/json": {
                          schema: {
                              $ref: "#/definitions/worktable_addCount"
                          }  
                      },
                  }
          } */
    let { data } = req.body;
    addCount(data)
        .then((result) => {
            if (result == 1) {
                res.sendStatus(200);
            } else {
                res.sendStatus(500);
            }
        })
        .catch((err) => {
            log.error(err);
            res.status(500).send(err);
        });
});

async function addCount(data) {
    const results = await ohana_instance.find({
        WORKTABLE_ID: data.WORKTABLE_ID,
    });
    let result = await ohana_instance.update(
        {
            WORKTABLE_ID: data.WORKTABLE_ID,
        },
        {
            COUNT: results[0].COUNT + 1,
        }
    );
    return result;
}

router.put("/", function (req, res, next) {
    // #swagger.tags = ['定时任务']
    // #swagger.summary = '更新列表'
    /* #swagger.security = [{
                   "JiangduJWT": []
      }] */
    /*	#swagger.requestBody = {
                  required: true,
                  content: {
                      "application/json": {
                          schema: {
                              $ref: "#/definitions/worktable_update"
                          }  
                      },
                  }
          } */
    const { data } = req.body;
    updateData(data)
        .then((result) => {
            if (result == 1) {
                res.sendStatus(200);
            } else {
                res.sendStatus(400);
            }
        })
        .catch((err) => {
            log.error(err);
            res.status(500).send(err);
        });
});

router.delete("/", function (req, res, next) {
    // #swagger.tags = ['定时任务']
    // #swagger.summary = '删除列表(必须传进ID数组)'
    /* #swagger.security = [{
                   "JiangduJWT": []
      }] */
    /*	#swagger.requestBody = {
                  required: true,
                  content: {
                      "application/json": {
                          schema: {
                              $ref: "#/definitions/worktable_delete"
                          }  
                      },
                  }
          } */
    const { data } = req.body;
    deleteData(data)
        .then((result) => {
            if (result == 1) {
                res.sendStatus(200);
            } else {
                res.sendStatus(400);
            }
        })
        .catch((err) => {
            log.error(err);
            res.status(500).send(err);
        });
});

async function getData(condition) {
    let result = [];
    if (!condition) {
        result = "请登录";
    } else {
        result = await ohana_instance.find(condition);
    }
    return result;
}

async function insertData(data) {
    data.WORKTABLE_ID = uunewid.v4();
    let result = await ohana_instance.insert(data);
    return result;
}

async function updateData(data) {
    let result = await ohana_instance.update(
        {
            WORKTABLE_ID: data.WORKTABLE_ID,
        },
        data
    );
    return result;
}

async function deleteData(data) {
    data.forEach((element) => {
        ohana_instance.raw(
            'delete from "' +
            tableName +
            "\" where WORKTABLE_ID = '" +
            element.WORKTABLE_ID +
            "'"
        );
        ohana_instance.raw(
            "delete from SAP_JIANGDU_COMBINED_NOTIFICATIONS where ID = '" +
            element.WORKTABLE_ID +
            "'"
        );
    });
    return 1;
}

module.exports = router;
